class SectionSweeper < ActionController::Caching::Sweeper
  observe Collection, Section, Document

  def after_save(record)
    if record.is_a?(Collection)
      record.sections.each do |section|
        expire_section(section)
      end
    elsif record.is_a?(Section)
      record.self_and_descendants.each do |section|
        expire_section(section)
      end
      expire_section(record.parent) if record.parent
    elsif record.is_a?(Document)
      expire_section(record.section)
    end
  end

  def expire_section(section)
    expire_page(:controller=>'sections', :action=>'show', :id=>section.to_param)
    
    # Delete all files in directory to remove all cached pages (pagination)
    pages_path = url_for(:controller=>'sections', :action=>'show',
      :id=>section.to_param, :page=>'1', :only_path=>true)
    raise Detective.view_source("#{self.class.name}#expire_section").inspect
    raise section_path(section).class.inspect
    raise url_for(:controller=>'collections', :action=>'show').inspect
    pages_dir = File.join(ActionController::Base.page_cache_directory,
      File.dirname(pages_path))
    Dir.glob(File.join(pages_dir, '*.html')) do |cached_page|
      File.delete(cached_page)
    end
  end
end

